package org.nus;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
 * Export data to a txt file.
 * @author Xiaohui Li
 *
 */
public class ExportAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		HttpSession session = request.getSession();
		// Set the headers.
		String filename = "result.txt";
		response.setContentType("application/x-download");
		response.setHeader("Content-Disposition",
				"attachment; filename=" + filename);
	
		//export data are put into session by ShowDataBetweenDatesAction action
		String exportData = (String) session.getAttribute("exportData");
		OutputStream out = response.getOutputStream();
		write(out, exportData);
		out.close();
		return null;
	}

	private void write(OutputStream out, String data) {
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
		try {
			writer.write(data);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private boolean compareDate(String date1, String date2) {
		try {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date d1 = df.parse(date1);
			Date d2 = df.parse(date2);
			if (d1.before(d2)) {
				return true;
			} else {
				return false;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return false;
	}

}